<?php

namespace App\Listener;

use App\AsyncTask\OcpcJobMessage;
use App\Event\RechargeEvent;
use App\Model\User;
use Swoole\Server;
use Hyperf\Process\ProcessCollector;
use App\Event\PubMomentEvent;
use App\Event\RegDoneEvent;
use App\Helpers\OcpcUtil;
use App\Model\Message;
use App\Model\Ocpc\OcpcOppo;
use App\Task\Ocpc\OcpcTask;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Utils\ApplicationContext;

/**
 * OCPC事件监听
 * @Listener
 */
class OcpcListener implements ListenerInterface
{
    public function listen(): array
    {
        return [
            //注册事件
            RegDoneEvent::class,
            RechargeEvent::class
        ];
    }

    /**
     * @param object $event
     */
    public function process(object $event)
    {
        $info = User::getUser($event->userId);
        if (!$info) return;
        $info = $info->toArray();
        $info['user_id'] = $info['id'];
        $info['pay_amount'] = 0;
        if ($event->eventType == 'recharge') {
            $info['pay_amount'] = ($event->rechargeRmb ?? 0) * 100;
        }
        $this->sendPipeMessage($info, $event->eventType);
        return;
    }

    public function sendPipeMessage($info, $eventType)
    {
        $container = ApplicationContext::getContainer();
        $server = $container->get(Server::class);
        //获取子进程编号
        $workerCount = $server->setting['worker_num'] + ($server->setting['task_worker_num'] ?? 0) - 1;
        if ($workerCount > 0) {
            for ($workerId = 0; $workerId <= $workerCount; ++$workerId) {
                //向其他子进程发送消息
                if ($server->worker_id != $workerId) {
                    $server->sendMessage(new OcpcJobMessage($info, $eventType), $workerId);
                    return;
                }
            }
        }
        /*
        //向其他进程发送消息
        if (class_exists(ProcessCollector::class)) {
            $processes = ProcessCollector::all();
            if ($processes) {
                $string = serialize(['info' => $info, 'eventType' => $eventType]);
                foreach ($processes as $process) {

                    dump(9);
                    $process->exportSocket()->send($string, 10);
                }
            }
        }
        */
    }
}
